package sms

import (
	"crypto/md5"
	"encoding/json"
	"fmt"
	"log"
	"private-domain-overseas-service/pkg/http"
	"strconv"
	"time"
)

type HrySmsService struct {
	Url       string
	Appkey    string
	Appsecret string
	Appcode   string
}

func NewHrySmsService() (*HrySmsService, error) {
	return &HrySmsService{
		Url:       "http://sms.huaruiyunapi.com",
		Appkey:    "PLFSxE",
		Appsecret: "6Be6v2",
		Appcode:   "1000",
	}, nil
}

// sign - 签名
func (s *HrySmsService) sign(timestamp int64) string {
	re := md5.Sum([]byte(s.Appkey + s.Appsecret + strconv.FormatInt(timestamp, 10)))
	return fmt.Sprintf("%x", re)
}

// Send - 发送短信
func (s *HrySmsService) Send(phoneNumber, templateID string, params []string) error {
	path := "/sms/batch/v1"
	msg := fmt.Sprintf("【慧赚赚】您的%s元体验大礼包已经开始曝光，预计%s结束，请及时前往APP内查看本次曝光详情", params[0], params[1])
	if templateID == "1" {
		msg = fmt.Sprintf("【慧赚赚】您的验证码是 ：%s，该验证码10分钟内有效", params[0])
	}

	// 当前时间戳
	timestamp := time.Now().UnixMilli()
	sign := s.sign(timestamp)
	data := map[string]interface{}{
		"sign":      sign,
		"timestamp": timestamp,
		"phone":     phoneNumber,
		"appcode":   s.Appcode,
		"appkey":    s.Appkey,
		"msg":       msg,
	}

	dataJson, _ := json.Marshal(data)

	log.Println("短信参数：" + string(dataJson))

	res, _ := http.PostRequest(s.Url+path, dataJson)

	log.Println("短信返回：" + string(res))

	return nil
}

// SendMessage - 发送短信
func (s *HrySmsService) SendMessage(phoneNumber, msg string, env string) error {
	// 必须正式服发才能发送短信
	//if env != "pro" {
	//	return nil
	//}

	path := "/sms/batch/v1"
	//msg = fmt.Sprintf("【慧赚赚】%s", msg)
	// 当前时间戳
	timestamp := time.Now().UnixMilli()
	sign := s.sign(timestamp)
	data := map[string]interface{}{
		"sign":      sign,
		"timestamp": timestamp,
		"phone":     phoneNumber,
		"appcode":   s.Appcode,
		"appkey":    s.Appkey,
		"msg":       msg,
	}

	dataJson, _ := json.Marshal(data)

	log.Println("短信参数：" + string(dataJson))

	res, _ := http.PostRequest(s.Url+path, dataJson)

	log.Println("短信返回：" + string(res))

	return nil
}

// @Description: 获取短信余额
// @receiver s
// @return error
func (s *HrySmsService) GetBalance() (int, string) {
	path := "/sms/balance/v1"
	timestamp := time.Now().UnixMilli()
	//data := map[string]interface{}{
	//	"appkey":    s.Appkey,
	//	"appcode":   s.Appcode,
	//	"sign":      s.sign(timestamp),
	//	"timestamp": timestamp,
	//}
	data := map[string]string{
		"appkey":    s.Appkey,
		"appcode":   s.Appcode,
		"sign":      s.sign(timestamp),
		"timestamp": strconv.FormatInt(timestamp, 10),
	}
	//jsonData, _ := json.Marshal(data)
	request, _ := http.GetRequest(s.Url+path, data, nil)
	var res struct {
		Appkey      string `json:"appkey"`
		Balance     string `json:"balance"`
		BalanceTime string `json:"balance_time"`
	}
	err := json.Unmarshal(request, &res)
	log.Println("余额返回：", string(request))
	if err != nil {
		return 0, ""
	}
	balance, _ := strconv.Atoi(res.Balance)
	return balance, res.BalanceTime
}
